#include"PipeEvent.h"

#include<unistd.h>
#include<fcntl.h>
#include<iostream>

using namespace tmms::network;

PipeEvent::PipeEvent(EventLoop *loop):Event(loop)
{
    int fd[2]={0,};
    auto ret  = ::pipe2(fd,O_NONBLOCK);
    if(ret<0)
    {
        std::cout<<"pipe open faild"<<std::endl;
        exit(-1);
    }
    fd_=fd[0]; //管道就是一端读fd[0] 一端写fd[1]，
    write_fd_ = fd[1]; 

    std::cout<<"hhhhh"<<std::endl;
}

PipeEvent::~PipeEvent()
{
    if(write_fd_>0){
        ::close(write_fd_);
        write_fd_ = -1;
    }
}

void PipeEvent::OnRead(){
    int64_t tmp;
    auto ret = ::read(fd_,&tmp,sizeof(tmp));
    if(ret<0)
    {
        std::cout<<"pipe read errorL" <<errno<<std::endl;
    }
    std::cout<<"pipe read tmp:"<<tmp<<std::endl;
}

void PipeEvent::OnClose() 
{
    if(write_fd_>0){
        ::close(write_fd_);
        write_fd_ = -1;
    }
}

void PipeEvent::OnError(const std::string &msg) 
{
    std::cout<<"error:"<<msg<<std::endl;
}

void PipeEvent::Wirte(const char* data,size_t len)
{
    std::cout<<"the data is "<<data<<"and the wirte_fd is "<< write_fd_<<std::endl;
     ::write(write_fd_,data,len);

}
